package com.chhuang.uresource.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupSave;
import com.chhuang.uresource.bean.ChUserQueryBean;
import com.chhuang.uresource.conts.SysConstants;
import com.chhuang.uresource.po.ChUser;
import com.chhuang.uresource.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.string.Md5Util;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("system/user")
public class SysUserController {
	private static final Log log = LogFactory.getLog(SysResourceController.class);
	
	@Autowired
	private IChUserService userService;
	
	/**
	 * 修改密码
	 * @param oldPassword
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/editPassword", method=RequestMethod.POST)
	public Object editPassword(String oldPassword, String password, HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		
		HttpSession session = request.getSession(false);
		String userId = (String) session.getAttribute(SysConstants.USER_ID);
		
		if(Assert.isValidString(userId) && Assert.isValidString(oldPassword) 
				&& Assert.isValidString(password)) {
			ChUser user = userService.findByPrimaryKey(userId);
			if(user != null) {
				if(Md5Util.md5(oldPassword, user.getUsername()).equals(user.getPassword())) {
					user.setPassword(Md5Util.md5(password, user.getUsername()));
					userService.update(user);
					json.put(SysConstants.Status.SUCCESS, true);
				}else {
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "原密码不正确");
				}
			}else {
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else {
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "参数有误");
		}
		
		log.debug(json);
		return json;
	}
	
	/**
	 * 添加管理员
	 * @param user
	 * @param bindingResult
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/addUser", method=RequestMethod.PUT)
	public Object addUser(@RequestBody @Validated(value={ValidGroupSave.class}) ChUser user, 
			BindingResult bindingResult, HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		
		HttpSession session = request.getSession(false);
		String userId = (String) session.getAttribute(SysConstants.USER_ID);
		String superAdminIds = SysConfig.getValue(SysConstants.Config.SUPER_ADMIN_ID);
		
		if(Assert.isValidString(superAdminIds) && superAdminIds.indexOf("<"+userId+">")>-1){
			if(!bindingResult.hasErrors()){
				String username = user.getUsername();
				if(Assert.isInvalidCollection(userService.findByUsername(username))) {
					String initPsw = SysConfig.getValue(SysConstants.Config.INIT_PASSWORD);
					String password = username+initPsw;
					user.setPassword(Md5Util.md5(password, username));
					user.setCreateTime(new Date());
					userService.save(user);
					json.put(SysConstants.Status.SUCCESS, true);
				}else {
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户名已存在");
				}
			}else {
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			}
		}else {
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "您的权限不够这个操作");
		}

		log.debug(json);
		return json;
	}
	
	/**
	 * 删除用户
	 * @param userIdStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/removeUser/{userIdStr}",method=RequestMethod.DELETE)
    public Object removeUser(@PathVariable("userIdStr") String userIdStr, HttpServletRequest request) throws Exception {
    	JSONObject json = new JSONObject();
    	
    	HttpSession session = request.getSession(false);
		String userId = (String) session.getAttribute(SysConstants.USER_ID);
		String superAdminIds = SysConfig.getValue(SysConstants.Config.SUPER_ADMIN_ID);
		if(Assert.isValidString(superAdminIds) && superAdminIds.indexOf("<"+userId+">")>-1){
	    	if(Assert.isValidString(userIdStr)){
	    		String[] userIds = userIdStr.split(SysConstants.Symbol.SEMICONLON);
	    		userService.deleteByPrimaryKeys(superAdminIds, userIds);
	    		json.put(SysConstants.Status.SUCCESS, true);
	    	}else {
	    		json.put(SysConstants.Status.SUCCESS, false);
	    		json.put(SysConstants.Status.RESULT, "参数有误");
	    	}
    	}else {
    		json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "您的权限不够这个操作");
    	}
    	
    	return json;
    }
	
	/**
	 * 用户分页列表
	 * @param search
	 * @param limit
	 * @param offset
	 * @param sort
	 * @param isDesc
	 * @param isOr
	 * @param draw
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getList",method=RequestMethod.GET)
	public Object getList(String search, Integer limit, Integer offset, 
			String sort, Boolean isDesc, Boolean isOr, Integer draw) throws Exception{
		JSONObject json = new JSONObject();
		
		ChUserQueryBean userQueryBean = new ChUserQueryBean();
		userQueryBean.setUsername(search);
		
		userQueryBean.setLimit(limit==null?10:limit);
		userQueryBean.setOffset(offset==null?0:offset);
		userQueryBean.setOr(isOr==null?true:isOr);
		userQueryBean.setSort(sort==null?"createTime":sort);
		userQueryBean.setDesc(isDesc==null?true:isDesc);
		
		QueryBean<ChUser> queryBean = userService.seniorQuery(userQueryBean);
		
		json.put(SysConstants.Status.SUCCESS, true);
		json.put(SysConstants.Status.RESULT, queryBean);
		json.put(SysConstants.Status.OTHER, draw);
		
		log.debug(json);
		return json;
	}
	
}
